/*
 * Description: 操作Table数据相关的工具函数
 * Author: wangyifei
 * DateCreated: 2024-03-28 16:31
 */

import React, { useCallback, useState } from 'react';
import type { TableRowSelection } from 'antd/es/table/interface';
import type { PagePayload } from '@/utils/request';

/**
 * 当检测到是在最后一页并且数据被清空时，页码减一
 * @param payload 列表接口参数
 * @param tableData 已保存的Table数据
 * @param handleList 删除的条目数
 * @returns -> { pageNo: number; pageSize: number }
 */
export function onTableDelete<T = any>(
	payload: PagePayload<T>,
	tableData: { list: any[]; total: number; pageCount?: number },
	handleList: any[]
) {
	const { list, total, pageCount } = tableData;
	const { pageNo, pageSize } = payload;

	const count = pageCount ?? Math.ceil(total / pageSize);

	if (count === pageNo && handleList.length >= list.length) {
		const totalPage = Math.ceil((total - handleList.length) / pageSize);
		const newPage = pageNo > totalPage ? totalPage : pageNo;
		return { ...payload, pageNo: newPage < 1 ? 1 : newPage, pageSize };
	} else {
		return { ...payload, pageNo, pageSize };
	}
}

/**
 * 表格跨页多选
 * @param config - {
 *  - primaryId: 表格主键，默认为:id
 *  - }
 * @returns - {
 *  - rowSelection: Table组件rowSelection属性所需要的配置对象
 * 	- selectedRowKeys: 已选中的 keys
 * 	- selectedRows: 已选中的 rows
 *  - clearSelected: 清除所有已选中的信息
 *  - }
 */
export function useTableSelect<T = any>(
	config: {
		primaryId?: string;
	} = {}
): {
	selectedRowKeys: React.Key[];
	selectedRows: T[];
	rowSelection: TableRowSelection<T>;
	clearSelected: () => void;
} {
	const { primaryId = 'id' } = config;

	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	const [selectedRows, setSelectedRows] = useState([]);

	const onSelect: TableRowSelection<T>['onSelect'] = useCallback(
		(record, selected) => {
			const newList = [...selectedRows];
			const findIndex = newList.findIndex((item) => item[primaryId] === record[primaryId]);

			if (selected && findIndex === -1) {
				newList.push(record);
			} else if (findIndex !== -1) {
				newList.splice(findIndex, 1);
			}
			setSelectedRowKeys(newList.map((item) => item[primaryId]));
			setSelectedRows(newList);
		},
		[selectedRows]
	);

	const onSelectAll: TableRowSelection<T>['onSelectAll'] = useCallback(
		(selected, _, changed) => {
			const newList = [...selectedRows];
			if (selected) {
				for (const row of changed) {
					if (!newList.find((item) => item[primaryId] === row[primaryId])) {
						newList.push(row);
					}
				}
			} else {
				for (const row of changed) {
					const findIndex = newList.findIndex((item) => item[primaryId] === row[primaryId]);
					if (findIndex !== -1) {
						newList.splice(findIndex, 1);
					}
				}
			}

			setSelectedRowKeys(newList.map((item) => item[primaryId]));
			setSelectedRows(newList);
		},
		[selectedRows]
	);

	return {
		selectedRowKeys,
		selectedRows,
		rowSelection: { selectedRowKeys, onSelectAll, onSelect },
		clearSelected: () => {
			setSelectedRowKeys([]);
			setSelectedRows([]);
		}
	};
}
